package com.example.linearlayoutdemo.network.auth.utils;

import android.os.Handler;
import android.os.Looper;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 线程管理工具类，用于处理后台任务和主线程切换
 */
public class ThreadManager {
    private static volatile ThreadManager instance;
    private final ExecutorService networkExecutor;
    private final Handler mainHandler;

    private ThreadManager() {
        // 创建网络请求线程池
        networkExecutor = Executors.newFixedThreadPool(3);
        // 创建主线程Handler
        mainHandler = new Handler(Looper.getMainLooper());
    }

    public static ThreadManager getInstance() {
        if (instance == null) {
            synchronized (ThreadManager.class) {
                if (instance == null) {
                    instance = new ThreadManager();
                }
            }
        }
        return instance;
    }

    /**
     * 执行网络请求任务
     */
    public void executeNetworkTask(Runnable task) {
        networkExecutor.execute(task);
    }

    /**
     * 在主线程执行任务
     */
    public void runOnMainThread(Runnable task) {
        if (Looper.myLooper() == Looper.getMainLooper()) {
            // 已经是主线程，直接执行
            task.run();
        } else {
            // 切换到主线程执行
            mainHandler.post(task);
        }
    }

    /**
     * 释放资源
     */
    public void release() {
        networkExecutor.shutdown();
        mainHandler.removeCallbacksAndMessages(null);
    }
}

